package com.zsrd.lessons.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsrd.lessons.domain.TsSubject;
import com.zsrd.lessons.mapper.TsSubjectMapper;
import com.zsrd.lessons.service.TsSubjectService;
import com.zsrd.system.domain.SysDept;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class TsSubjectServiceImpl extends ServiceImpl<TsSubjectMapper, TsSubject> implements TsSubjectService {

    @Override
    public List<TsSubject> getAllSubjectList() {

        List<TsSubject> sysDepts = baseMapper.getAllSubjects();
        //collect1里面的数据重新递归
        Stream<TsSubject> sysDeptStream = sysDepts.stream().filter(item -> item.getDelFlag().equals(0));
        ;
        //返回一个stream流方式通过.map方法将list里面的值赋值进去然后返回一个新的list集合
        List<TsSubject> collect2 = sysDeptStream.map(adminSysMenu -> {
            //将上面list查寻的数据调用下面递归的方法依次进行 从0开始 到结束 才退出返回一个新的list
            adminSysMenu.setChildren(cycleTree(sysDepts, adminSysMenu));
            return adminSysMenu;
        }).collect(Collectors.toList());
        //查看这个集合里相同的元素
        List<TsSubject> collect1 = Stream.concat(collect2.stream(), sysDepts.stream())
                .distinct()
                .collect(Collectors.toList());
        //删除多余元素
        for (int i = 0; i < collect1.size(); i++) {
            TsSubject sysDept2 = collect1.get(i);
            if (sysDept2.getChildren()!=null) {
                List<TsSubject> children = sysDept2.getChildren();
                for (TsSubject child : children) {
                    collect2.remove(child);
                }
            }
        }
//        collect2.stream().sorted(Comparator.comparingLong(TsSubject::getOrderNum));
        return collect2;

    }

    // 递归遍历
    private List<TsSubject> cycleTree(List<TsSubject> list, TsSubject tsSubject) {
        Stream<TsSubject> adminSysMenuStream = list.stream()
                .filter(items -> items.getSubjectParentId().equals(tsSubject.getId()))
                .filter(items -> items.getDelFlag().equals(0))
                ;
        //如果相等就进入里面 将这条数据set进去
        List<TsSubject> collect = adminSysMenuStream.map(adminSysMenu -> {
            adminSysMenu.setChildren(cycleTree(list, adminSysMenu));
            //然后返回 一直到没有了以后才返回一次list
            return adminSysMenu;
        }).collect(Collectors.toList());
        return collect;

    }
}
